package org.webrtc.mqttclientsample;

import java.net.URI;
import java.nio.CharBuffer;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import org.webrtc.mqttclientsample.Message.MessageType;

import com.bieyang.anjia.ui.activity.App;
import com.bieyang.anjia.utils.ApplicationUtils;
import com.bieyang.anjia.utils.SubUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.util.Log;

public class ZZClient extends WebSocketClient {

	private SocketStateCallBack mCallBack;
	private String mLogiNname;

	private void showLog(String msg) {
		Log.i("WebSocket", msg);
	}

	public ZZClient(URI serverUri, Draft draft) {
		super(serverUri, draft);
	}

	public ZZClient(URI serverURI) {
		super(serverURI);
	}

	public ZZClient(URI serverUri, String loginName) {
		super(serverUri);
		mLogiNname = loginName;
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		showLog("opened connection");
		if (mCallBack != null) {
			mCallBack.onOpen(handshakedata);
		}
		startKeepAliveProcess();

	}

	@Override
	public void onMessage(String message) {

		lastActive = System.currentTimeMillis();

		if (message == null || "".equals(message.toString().trim())) {

			return;
		}
		showLog("rec:" + message);

		Message msg = MessageBuilder.build(message);
		
		LogUtis.log("type:"+msg.getType());
		if (mCallBack != null) {
			mCallBack.onReceiveMessage(msg);
		}

	}

	@Override
	public void onFragment(Framedata fragment) {
//		showLog("received fragment: "
//				+ new String(fragment.getPayloadData().array()));
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {

		showLog("Connection closed by " + (remote ? "remote peer" : "us"));
		if (mCallBack != null) {
			mCallBack.onClose(code, reason, remote);
		}
	}

	@Override
	public void onError(Exception ex) {
		ex.printStackTrace();
		showLog("onError " + ex.getMessage());
		if (mCallBack != null) {
			mCallBack.onError(ex);
		}
	}

	public void login(String username, String password) {
		mLogiNname = username;
		Message login = new Message();
		login.setFrom(username);
		login.setType(MessageType.LOGIN);
		Gson gson = new Gson();
		String str = gson.toJson(login);
		send(str);

	}

	public void sendTextMessage(String to, String text) {
		Message msg = new Message();
		msg.setFrom(mLogiNname);
		msg.setTo(to);
		msg.setType(MessageType.CHAT);
		msg.setContent(text);
		Gson gson = new Gson();
		String str = gson.toJson(msg);
		send(str);
	}

	public void sendPhoneMessage(String to, String text) {
		Message msg = new Message();
		msg.setFrom(mLogiNname);
		msg.setTo(to);
		msg.setType(MessageType.PHONE);
		msg.setContent(text);
		Gson gson = new Gson();
		String str = gson.toJson(msg);
		send(str);
		LogUtis.log("sendto:"+to+"-->"+text);
	}

	public void setSocketCallBack(SocketStateCallBack callBack) {
		this.mCallBack = callBack;
	}

	Thread keepAliveThread;
	long lastActive;

	void startKeepAliveProcess() {
		int keepAliveInterval = ZZConfig.AliveInterval;
		if (keepAliveInterval > 0) {
			KeepAliveTask task = new KeepAliveTask(keepAliveInterval);
			this.keepAliveThread = new Thread(task);
			task.setThread(this.keepAliveThread);
			this.keepAliveThread.setDaemon(true);
			this.keepAliveThread.setName("websocket Keep Alive (" + ")");
			this.keepAliveThread.start();
		}
	}

	private class KeepAliveTask implements Runnable {
		private int delay;
		private Thread thread;

		public KeepAliveTask(int paramInt) {
			this.delay = paramInt;
		}

		protected void setThread(Thread thread) {
			this.thread = thread;
		}

		public void run() {
			try {
				Thread.sleep(15000L);
			} catch (InterruptedException localInterruptedException) {
			}
		//new add -----------------------------
			 while(true){
				 Log.d("client", ""+ZZClient.this.isClosed());			 
				 if((!(ZZClient.this.isClosed()))
							&& (ZZClient.this.keepAliveThread == this.thread)){
					 synchronized (ZZClient.this) {
							if (System.currentTimeMillis() - ZZClient.this.lastActive >= this.delay) {
								try { 
									ZZClient.this.send("");
									LogUtis.log("send active.......");
								} catch (Exception localException) {
								}
							}
						}
						try {
							Thread.sleep(this.delay);
						} catch (InterruptedException localInterruptedException1) {
						}
				 }else{
					 //如果网络好的情况则重登陆
					 if(ApplicationUtils.netState(App.mContext)){
					  Log.d("rtc_login", "login:"+SubUtils.getUuid(App.mContext));					  
					  MessageService.startService(App.mContext, SubUtils.getUuid(App.mContext)); 
						try {
							Thread.sleep(10000L);
						} catch (InterruptedException localInterruptedException) {
						}
					 }
				 }
			 }
			//new ----------------------------
						 
		}
	}

	public void setLastActive(long s) {
		this.lastActive = s;
	}
}